package com.xnck.example.jertest.util;

import com.xiaoleilu.hutool.StrUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SignUtil {

    /**
     * 生成签名
     * @param appid 应用程序唯一ID
     * @param token 应用程序的私钥
     * @param millis 时间戳
     * @return
     * @throws Exception
     */
    public static String generate(String appid, String token, long millis) throws Exception {
        String timestamp = String.valueOf(millis);
        String signature = null;
        if (StrUtil.isNotBlank(token) && StrUtil.isNotBlank(timestamp)
                && StrUtil.isNotBlank(appid)) {
            List<String> srcList = new ArrayList<String>();
            srcList.add(timestamp);
            srcList.add(appid);
            srcList.add(token);
            // 按照字典序逆序拼接参数
            Collections.sort(srcList);
            Collections.reverse(srcList);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < srcList.size(); i++) {
                sb.append(srcList.get(i));
            }
            signature = SHA1Util.encode(sb.toString());
            srcList.clear();
        }
        return signature;
    }
}
